﻿using System;
using System.IO;
using System.Reflection;
using System.Security.Principal;
using System.Web.Http.SelfHost;
using AutoFacWrapper;
using Log4Wrapper;
using ZLWeb.WebApiConfigration;
using ZLWeb.WebApiConfigration.SelfHostConfig;
using ZLWeb.WebApiConfigration.WebapiAppsetting;
using ZLWeb.WebApiControllers;
using ZLWeb.WebApiInfrastructure.Filter;

namespace ZLWeb.WebApiSelfHostService
{
    /// <summary>
    ///     启动类
    /// </summary>
    public class Bootstrapper
    {
        public static void Run()
        {
            LoadConfg();
            var config = SelfHostConfig.GlobalHostConfig.HttpSelfHostConfiguration;
            RegisterModules(config);

            RegisterFilters(config);
            Service_Start(config);
        }

        /// <summary>
        ///     IOC注册模块
        /// </summary>
        private static void RegisterModules(HttpSelfHostConfiguration config)
        {
            ClassFactory.RegisterAssemblis(Assembly.Load("ZLWeb.WebApiRepository"));
            ClassFactory.RegisterDependencyResolver(config.DependencyResolver);
            ClassFactory.RegisterApiControllers(Assembly.Load("ZLWeb.WebApiControllers"));
           
          
        }

        /// <summary>
        ///     LOAD配置文件
        /// </summary>
        private static void LoadConfg()
        {
            var configpath = AppDomain.CurrentDomain.BaseDirectory;
#if DEBUG
            if (configpath.LastIndexOf(@"bin", StringComparison.Ordinal) == -1)
            {
                configpath = configpath + @"bin";
            }
#endif
            ZLLogger.SetConfig(new FileInfo(configpath + "\\Log4Config.xml"));

            PipeWebServiceConfig.SetConfig(new FileInfo(configpath + "\\ZLWebPipeConfig.xml"));


            ZLWebApiAppSetting.GetAppSetting().LoadData(configpath + "\\ZLWebApiAppSetting.xml");
        }

        /// <summary>
        ///     注册AOP
        /// </summary>
        private static void RegisterFilters(HttpSelfHostConfiguration config)
        {
            config.Filters.Add(new ExceptionAttribute());
            config.Filters.Add(new SessionValidateAtrribute());
            config.Filters.Add(new RandomCodeAtrribute());
            config.Filters.Add(new RunLogAtrribute());
        }

        private static void Service_Start(HttpSelfHostConfiguration config)
        {
            AttributeRoutingConfig.Start(); //手动注册特性路由

            var server = new HttpSelfHostServer(config);
            /**
            * 当前用户是管理员的时候，直接启动应用程序
            * 如果不是管理员，则使用启动对象启动程序，以确保使用管理员身份运行
            */
            //获得当前登录的Windows用户标示
            var identity = WindowsIdentity.GetCurrent();
            var principal = new WindowsPrincipal(identity);
            //判断当前登录用户是否为管理员
            if (principal.IsInRole(WindowsBuiltInRole.Administrator))
            {
                //如果是管理员，则直接运行
                server.OpenAsync().Wait();
                ZLLogger.WriteLog("服务开启，当前时间为：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss "));
            }
            else
            {
                ZLLogger.WriteLog("由于缺少管理员权限，服务未能开启，当前时间为：" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss "));
            }
            Console.ReadLine();
        }
    }
}